<template>
  <div class="boxrobot">
    <div class="charts" ref="charts"></div>
  </div>
</template>

<script setup lang="ts">
import * as echarts from "echarts";
import { ref, watch, nextTick } from "vue";
import { RobotApi } from "@/api/map/usecount";

/* 1. 接收城市名 */
const props = defineProps<{ city: string }>();

/* 2. DOM */
const charts = ref<HTMLDivElement>();
let myChart: echarts.ECharts;

/* 3. 绘图函数 */
async function drawBar() {
  const res = await RobotApi.getRobotUseCount({ province: props.city });
  const xAxisData = res.map((i) => Object.keys(i)[0]);
  const barData = res.map((i) => Number(i[Object.keys(i)[0]]));
  const lineData = [...barData]; // 折线同数据，按需改

  const option: echarts.EChartsOption = {
    title: {
      text: "使用情况",
      left: "left",
      top: "5%",
      textStyle: { color: "#fff", fontSize: 14 },
    },
    tooltip: { trigger: "axis" },
    grid: {
      top: "20%",
      left: "10%",
      right: "10%",
      bottom: "0%",
      containLabel: true,
    },
    xAxis: { type: "category", data: xAxisData, axisLabel: { color: "#fff" } },
    yAxis: [
      {
        type: "value",
        interval: 1,
        axisLabel: { color: "#fff" },
        splitLine: { show: false },
      },
      { type: "value", axisLabel: { show: false }, splitLine: { show: false } },
    ],
    series: [
      {
        name: "柱状图",
        type: "bar",
        data: barData,
        itemStyle: { color: "#594AC7" },
      },
      {
        name: "折线图",
        type: "line",
        yAxisIndex: 1,
        data: lineData,
        lineStyle: { color: "#f1c40f" },
        symbol: "none",
      },
    ],
  };

  if (!myChart) myChart = echarts.init(charts.value!);
  myChart.setOption(option, true);
}

/* 4. 首次 + 城市变化立即刷新 */
nextTick(drawBar);
watch(() => props.city, drawBar);
</script>
<style scoped lang="scss">
.boxrobot {
  width: 100%;
  height: 100%;

  // background-color: rgb(161, 127, 255);

  .charts {
    height: 100%;
  }
}
</style>
